<?php
class PlacesController extends AppController {
  // property related to upload image
  public $pathPrefix;
  public $pathImage;
  public $fieldImage;
  public $errorUpload;
  public $resizedPrefix;
  public $thumbPrefix;

  public function beforeFilter() {
    parent::beforeFilter();
    //$this->Auth->allow('index', 'view');
    $this->Auth->allow('*');

    if ( $this->Auth->user('id') ) {
      $this->Auth->allow('attending', 'add');
    }

    $this->paginate['limit'] =
        Configure::read('infojabotabek.max_paginate_places');

    $relpath = $this->webroot .
               Configure::read('infojabotabek.images_url_relative_path');
    Configure::write('infojabotabek.images_url_relative_path', $relpath);
  }
    
  public function beforeRender() {    
    $plugin = isset($this->params['plugin']) ?
              $this->params['plugin'] . '/' : '';
    $this->set('urlController', $this->webroot . $plugin .
                                $this->params['controller']);

    parent::beforeRender();
  }

	public function index() {
    $this->layout = 'front';
    Configure::write('infojabotabek.is_front', true);
    Configure::write('infojabotabek.show_map', true);

    $this->paginate['order'] = 'Place.created DESC';
    $places = $this->paginate();
    Configure::write('infojabotabek.front.places', $places);
	}

	public function view($id = null, $type = 'html') {
    $this->layout = 'single';
    Configure::write('infojabotabek.is_single', true);
    Configure::write('infojabotabek.show_map', true);
    Configure::write('infojabotabek.map_type', 'view');
    Configure::write('infojabotabek.disqus_identifier', $id);

    $place = $this->Place->read(null, $id);
		if (empty($place)) {
			$this->Session->setFlash(__('Invalid event', true), 'error');
			$this->redirect(array('action' => 'index'));
		}
    Configure::write('infojabotabek.single.place', $place);

		$this->set('place', $place);
    $this->set('title_for_layout', $place['Place']['name']);

    // if printing url is requested
    if ($type == 'print') {
      $this->layout = 'single.print';
      $this->render('view.print');
    }
	}

  public function dashboard($id = null) {
    $this->Place->Behaviors->attach('Containable');
    $event = $this->Place->find('first', array(
      'conditions' => array(
        'Event.id' => $id
      ),
      'contain' => array(
        'EventParticipant' => array(
          'User'
        )
      )
    ));

		if (empty($event)) {
			$this->Session->setFlash(__('Invalid event', true), 'error');
			$this->redirect(array('action' => 'index'));
		}

		$this->set('event', $event);
  }

	public function add() {
    $this->layout = 'single';
    Configure::write('infojabotabek.is_single', true);
    Configure::write('infojabotabek.show_map', true);
    Configure::write('infojabotabek.map_type', 'add');
    // set the Model fields information for ijform helper
    $this->set('fields', $this->Place->fields);
    $this->helpers[] = 'ijform';

		if (!empty($this->data)) {
			$this->Place->create();

      // save logo first
      if ( is_array($this->data['Place']['logo_filename']) &&
           !empty($this->data['Place']['logo_filename']['tmp_name']) )
      {
        $logo = $this->__handleUploadImage(
                         $this->data['Place']['logo_filename']['error'],
                         $this->data['Place']['logo_filename']['tmp_name'],
                         $this->data['Place']['logo_filename']['type']);
        if ( !$logo ) {
          $this->data['Place']['logo_filename'] = '';
        } else {
          $this->data['Place']['logo_filename'] = $logo;
        }
      }

			if ($this->Place->save($this->data)) {

        // save video
        if ( isset($this->data['Place']['PlaceImage']['imagename']['name']) && 
             !empty($this->data['Place']['PlaceImage']['imagename']['name']) )
        {
          $imgname = $this->data['Place']['PlaceImage']['imagename']['name'];
          $tmps = $this->data['Place']['PlaceImage']['imagename']['tmp_name'];
          $errors = $this->data['Place']['PlaceImage']['imagename']['error'];
          $types = $this->data['Place']['PlaceImage']['imagename']['type'];

          foreach ($imgname as $key => $name) {
            if ( ($s = $this->__handleUploadImage($errors[$key],
                       $tmps[$key], $types[$key])) !== FALSE )
            {
              $saved_img = array(
                  'imagename' => $s, 'place_id' => $this->Place->id
              );
              $this->Place->PlaceImage->create();
              $this->Place->PlaceImage->save($saved_img);
            }
          }
        }

        // save youtube video id
        if ( isset($this->data['Place']['PlaceVideo']['youtube_id']) &&
             !empty($this->data['Place']['PlaceVideo']['youtube_id']) )
        {
            $saved_video = array();
            foreach ($this->data['Place']['PlaceVideo']['youtube_id'] as $k => $v) {
              $saved_video[$k] = array(
                'place_id' => $this->Place->id,
                'youtube_id' => $v
              );
            }
            $this->Place->PlaceVideo->create();
            $this->Place->PlaceVideo->saveAll($saved_img);
        }

				$this->Session->setFlash($this->msg['save_success'], 'success');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash($this->msg['save_fail'], 'error');
			}
		}
	}

	public function edit($id = null) {
    Configure::write('infojabotabek.is_single', true);
    Configure::write('infojabotabek.show_map', true);
    Configure::write('infojabotabek.map_type', 'add');

		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid event', true));
			$this->redirect(array('action' => 'index'));
		}

		if (!empty($this->data)) {
      $this->Place->id = $id;

      // save logo first
      if ( is_array($this->data['Place']['logo_filename']) ) {
        $logo = $this->__handleUploadImage(
                         $this->data['Place']['logo_filename']['error'],
                         $this->data['Place']['logo_filename']['tmp_name'],
                         $this->data['Place']['logo_filename']['type']);
        if ( !$logo ) {
          $this->data['Place']['logo_filename'] = '';
        } else {
          $this->data['Place']['logo_filename'] = $logo;
        }
      }

			if ($this->Place->save($this->data)) {

        if ( isset($this->data['Place']['PlaceImage']['imagename']['name']) && 
             !empty($this->data['Place']['PlaceImage']['imagename']['name']) )
        {
          $imgname = $this->data['Place']['PlaceImage']['imagename']['name'];
          $tmps = $this->data['Place']['PlaceImage']['imagename']['tmp_name'];
          $errors = $this->data['Place']['PlaceImage']['imagename']['error'];
          $types = $this->data['Place']['PlaceImage']['imagename']['type'];

          foreach ($imgname as $key => $name) {
            if ( ($s = $this->__handleUploadImage($errors[$key],
                       $tmps[$key], $types[$key])) !== FALSE )
            {
              $saved_img = array(
                  'imagename' => $s, 'place_id' => $this->Place->id
              );
              $this->Place->PlaceImage->create();
              $this->Place->PlaceImage->save($saved_img);
            }
          }
        }

				$this->Session->setFlash('Berhasil disimpan', 'success');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(
            'Tidak berhasil disimpan. Coba lagi!', 'error');
			}
		}

		if (empty($this->data)) {
			$this->data = $this->Place->read(null, $id);
      $this->set('event', $this->data);
		}
	}

	public function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid event', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Place->delete($id)) {
			$this->Session->setFlash(__('Event berhasil dihapus', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Event tidak berhasil dihapus', true));
		$this->redirect(array('action' => 'index'));
	}

  function delImage($id, $event_id) {
    $this->Session->setFlash('Gambar tidak berhasil terhapus', 'error');

    $this->Place->PlaceImage->id = $id;
    $imagename = $this->Place->PlaceImage->field($this->fieldImage);
    if ( $this->Place->PlaceImage->delete($id) ) {
      @unlink($this->pathPrefix . DS . $imagename);
      @unlink($this->pathPrefix . DS . $this->resizedPrefix . $imagename);
      @unlink($this->pathPrefix . DS . $this->thumbPrefix . $imagename);
      $this->Session->setFlash('Gambar berhasil terhapus', 'success');
    }
    $this->redirect(array('action' => 'edit', $event_id));
  }

  public function updateLatLng($id) {
    Configure::write('debug', 2);
    $this->layout = 'ajax';

    $data = array(
      'lat' => $this->params['form']['lat'],
      'lng' => $this->params['form']['lng']
    );
    $result = 0;
    $this->Place->id = $id;
    if ( $this->Place->save($data, array(
          'validate' => false, 'callback' => false,
          'fieldList' => array('lat', 'lng'))) )
    {
        $result = 1;
    }

    $this->set('result', $result);
  }

  public function unsetLatLng($id) {
    $this->autoRender = false;
    $this->Place->id = $id;
    $data = array(
      'lat' => null,
      'lng' => null
    );
    $this->Place->save($data, array(
      'validate' => false, 'callback' => false,
      'fieldList' => array('lat', 'lng')
    ));
  }

  private function __handleUploadImage($error_code, $tmp_name, $type) {
    $error = array();
    $possible_errors = array(
      1 => 'php.ini max file exceeded',
      2 => 'html form max file size exceeded',
      3 => 'file upload was only partial',
      4 => 'no file was attached'
    );

    // check for PHP's built-in uploading errors
    if ( $error_code > 0 ) {
      $error[] = $possible_errors[$error_code];
    }

    // check that the file we're working on really was the subject of an HTTP upload
    if ( !@is_uploaded_file($tmp_name) ) {
      $error[] = 'Not an HTTP upload';
    }

    // check if uploaded file is in fact an image
    if ( !@getimagesize($tmp_name) ) {
      $error[] = 'Only image uploads are allowed';
    }

    // check if our target directory is writeable
    if ( !is_writable(Configure::read('infojabotabek.images_path')) ) {
      $error[] = 'Target upload is not writeable.';
    }

    if ( empty($error) ) {
      // Make a unique filename for the uploaded files and check it is not already
      // taken.

      // new filename
      $type_parts = explode('/', $type);
      $filename = md5(mktime()) . '.' . $type_parts[1];
      $newpath = Configure::read('infojabotabek.images_path') . $filename;

      // error moving uploaded file
      if ( !@move_uploaded_file($tmp_name, $newpath) ) {
        //$this->errorUpload = 'Receiving directory insufficient permission';
        return false;
      }
      // resizing
      $this->_resizeImage($filename);

      return $filename;
    } else {
      //$this->errorUpload = $error;
      return false;
    }
  }
}
